<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

/**

 * @property integer $id
 * @property string $name
 * @property string $slug
 * @property string $description
 * @property integer $status
 * @property integer $sort
 * @property Carbon $created_at
 * @property Carbon $updated_at
 * @property Collection $permissions
 *
 */
class Role extends Model
{
    protected $guarded = [];

    /**
     * 角色拥有的管理员
     */
    public function admins(): BelongsToMany
    {
        return $this->belongsToMany(Admin::class, 'admin_has_roles', 'role_id', 'admin_id')
           ;
    }

    /**
     * 角色拥有的权限
     */
    public function permissions(): BelongsToMany
    {
        return $this->belongsToMany(Permission::class, 'role_has_permissions', 'role_id', 'permission_id');
    }

    /**
     * 为角色分配权限
     */
    public function assignPermissions(array $permissionIds): void
    {
        $this->permissions()->sync($permissionIds);
    }

    /**
     * 检查角色是否有某个权限
     */
    public function hasPermission($permissionSlug)
    {
        return $this->permissions->contains('slug', $permissionSlug);
    }

    /**
     * 获取角色的权限
     */
    public function getPermissionIds(): array
    {
        return $this->permissions()->pluck('id')->toArray() ?? [];
    }
}
